const express = require('express');
const router = express.Router();

const OrderPrisma = require('../models/OrderPrisma');
const PackagePrisma = require('../models/PackagePrisma');
const UserPrisma = require('../models/UserPrisma');
const { authenticateToken } = require('../middleware/auth');
const ResponseHelper = require('../utils/response');
const WechatPayService = require('../utils/WechatPayService');

/**
 * 发放套餐权益
 * @param {Object} options 处理选项
 * @param {number} options.userId 用户ID
 * @param {import('../models/PackagePrisma')} options.packageData 套餐数据
 * @param {import('../models/UserPrisma')} [options.user] 用户数据
 */
const grantPackageBenefits = async ({ userId, packageData, user }) => {
  if (!packageData) {
    return;
  }

  const creditsAmount = parseInt(packageData.credits_amount, 10) || 0;

  if (packageData.package_type === 'chat_message') {
    await UserPrisma.addChatCredits(userId, creditsAmount);
    console.log(`套餐权益发放: 用户${userId}增加${creditsAmount}条聊天消息额度`);
  } else if (packageData.package_type === 'contact_view') {
    await UserPrisma.addContactViewCredits(userId, creditsAmount);
    console.log(`套餐权益发放: 用户${userId}增加${creditsAmount}次查看手机号次数`);
  } else if (packageData.package_type === 'local_service') {
    await UserPrisma.addLocalServiceCredits(userId, creditsAmount);
    console.log(`套餐权益发放: 用户${userId}增加${creditsAmount}条本地服务发布次数`);
  } else {
    await UserPrisma.addCredits(userId, creditsAmount);
    console.log(`套餐权益发放: 用户${userId}增加${creditsAmount}条发布额度`);
  }

  const currentUser = user || await UserPrisma.findById(userId);
  if (currentUser && currentUser.status === 'inactive') {
    await UserPrisma.activate(userId);
    console.log(`套餐权益发放: 用户${userId}已自动激活`);
  }
};

/**
 * 接口 9: 创建订单
 * POST /api/v1/orders
 *
 * 输入: package_id
 * 逻辑: 创建一条 orders 记录，状态为 pending。集成微信支付 SDK，调用统一下单接口，生成支付参数返回给小程序
 */
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { package_id } = req.body;
    const userId = req.user.id;

    // 验证必填参数
    if (!package_id) {
      return ResponseHelper.validationError(res, ['package_id 是必填参数']);
    }

    // 验证套餐是否存在且上架
    const packageData = await PackagePrisma.findById(package_id);
    if (!packageData) {
      return ResponseHelper.notFound(res, '套餐不存在');
    }

    if (!packageData.is_active) {
      return ResponseHelper.error(res, '套餐已下架', 400);
    }

    // 验证用户是否存在
    const user = await UserPrisma.findById(userId);
    if (!user) {
      return ResponseHelper.unauthorized(res, '用户不存在');
    }

    const packagePrice = Number(packageData.price);
    if (Number.isNaN(packagePrice) || packagePrice < 0) {
      return ResponseHelper.serverError(res, '套餐价格配置异常', new Error(`Invalid package price: ${packageData.price}`));
    }
    const isFreePackage = packagePrice === 0;

    if (!isFreePackage && !user.openid) {
      return ResponseHelper.error(res, '用户未绑定微信，无法支付', 400);
    }

    if (isFreePackage) {
      const order = await OrderPrisma.create({
        user_id: userId,
        package_id,
        amount: 0,
        status: 'paid',
        payment_method: 'free',
        paid_at: new Date()
      });

      await grantPackageBenefits({ userId, packageData, user });

      return ResponseHelper.success(res, {
        order: order.toJSON(),
        payment_required: false,
        payment_params: null
      }, '订单创建成功');
    }

    // 创建订单
    const orderData = {
      user_id: userId,
      package_id,
      amount: packagePrice,
      status: 'pending',
      payment_method: 'wechat'
    };

    const order = await OrderPrisma.create(orderData);

    // 初始化微信支付服务
    const wechatPayService = new WechatPayService();

    // 准备微信支付下单数据
    const payOrderData = {
      amount: packagePrice,
      description: `购买套餐：${packageData.title}`,
      outTradeNo: order.order_number,
      openid: user.openid,
      timeExpire: new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30分钟后过期
    };

    // 调用微信支付下单
    const payResult = await wechatPayService.createOrder(payOrderData);

    if (!payResult.success) {
      // 支付下单失败，删除订单或标记为失败
      await OrderPrisma.update(order.id, { status: 'failed' });
      return ResponseHelper.error(res, `支付下单失败：${payResult.error}`, 400);
    }

    // 生成小程序支付参数
    const paymentParams = wechatPayService.generatePaymentParams(payResult.prepayId);

    ResponseHelper.success(res, {
      order: order.toJSON(),
      payment_required: true,
      payment_params: paymentParams
    }, '订单创建成功');

  } catch (error) {
    console.error('创建订单错误:', error);
    ResponseHelper.serverError(res, '创建订单失败', error);
  }
});

/**
 * 获取用户订单列表
 * GET /api/v1/orders
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;

    const result = await OrderPrisma.findByUserId(userId, {
      page: parseInt(page),
      limit: parseInt(limit),
      include: { package: true }
    });

    ResponseHelper.success(res, {
      orders: result.orders.map(order => order.toJSON()),
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: result.total,
        totalPages: Math.ceil(result.total / parseInt(limit))
      }
    }, '获取订单列表成功');

  } catch (error) {
    console.error('获取订单列表错误:', error);
    ResponseHelper.serverError(res, '获取订单列表失败', error);
  }
});

/**
 * 根据ID获取订单详情
 * GET /api/v1/orders/:id
 */
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    const order = await OrderPrisma.findById(id, {
      include: { user: true, package: true }
    });

    if (!order) {
      return ResponseHelper.notFound(res, '订单不存在');
    }

    // 验证订单是否属于当前用户
    if (order.user_id.toString() !== userId.toString()) {
      return ResponseHelper.forbidden(res, '无权访问此订单');
    }

    ResponseHelper.success(res, {
      order: order.toJSON()
    }, '获取订单详情成功');

  } catch (error) {
    console.error('获取订单详情错误:', error);
    ResponseHelper.serverError(res, '获取订单详情失败', error);
  }
});

/**
 * 模拟支付接口
 * POST /api/v1/orders/:id/mock-payment
 */
router.post('/:id/mock-payment', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.id;

    // 获取订单
    const order = await OrderPrisma.findById(id, {
      include: { user: true, package: true }
    });

    if (!order) {
      return ResponseHelper.notFound(res, '订单不存在');
    }

    // 验证订单是否属于当前用户
    if (order.user_id.toString() !== userId.toString()) {
      return ResponseHelper.forbidden(res, '无权访问此订单');
    }

    // 检查订单状态
    if (order.status !== 'pending') {
      return ResponseHelper.error(res, '订单状态不允许支付', 400);
    }

    // 模拟支付成功，更新订单状态
    const updatedOrder = await OrderPrisma.updateStatus(id, 'completed');

    // 获取用户信息
    const user = await UserPrisma.findById(userId);

    if (user) {
      // 根据套餐类型增加不同的额度
      if (order.package.package_type === 'chat_message') {
        // 聊天消息套餐，增加聊天消息额度
        await UserPrisma.addChatCredits(userId, order.package.credits_amount);
        console.log(`模拟支付：用户${userId}增加${order.package.credits_amount}条聊天消息次数`);
      } else if (order.package.package_type === 'contact_view') {
        // 查看手机号套餐，增加查看次数
        await UserPrisma.addContactViewCredits(userId, order.package.credits_amount);
        console.log(`模拟支付：用户${userId}增加${order.package.credits_amount}次查看手机号次数`);
      } else {
        // 其他套餐，增加发布额度
        await UserPrisma.addCredits(userId, order.package.credits_amount);
        console.log(`模拟支付：用户${userId}增加${order.package.credits_amount}条发布次数`);
      }

      // 如果用户状态为 inactive，自动激活用户
      if (user.status === 'inactive') {
        await UserPrisma.activate(userId);
        console.log(`模拟支付：用户${userId}已自动激活`);
      }
    }

    ResponseHelper.success(res, {
      order: updatedOrder.toJSON(),
      message: '支付成功'
    }, '支付成功');

  } catch (error) {
    console.error('模拟支付错误:', error);
    ResponseHelper.serverError(res, '支付失败', error);
  }
});

module.exports = router;
module.exports.__testables__ = {
  grantPackageBenefits
};
